<?php defined('SYSPATH') or die('No direct script access.');

class Controller_OpenLogin extends Controller_Template
{
//    private $_version = '1.0.7';

    public function __construct ($request, $response)
    {
        $this->template = 'smarty:www/homepage';
        parent::__construct($request, $response);
    }

    public function before()
    {
        parent::before();
//        $this->template->set('version', $this->_version);
    }

    //登录
    public function action_login($type)
    {
        $query = $this->request->query();
        $utype = strtoupper(Arr::get($query,'type','tourist'));
        $url = OpenLogin::instance($type)->get_login_url($utype);
        if (empty($url))
        {
            $this->msg('系统发请错误，请稍后再试');
        }
        else
        {
            $this->msg('', $url);
        }
    }

    //登录回调
    public function action_callback($type)
    {
        $query = $this->request->query();
        $access_token = OpenLogin::instance($type)->get_access_token();
        if (empty($access_token))
        {
            $this->msg('获取授权出错', '/');
        }
        $openid = OpenLogin::instance()->get_openid($access_token);
        if (empty($openid))
        {
            $this->msg('获取用户出错', '/');
        }
        
        $user = OpenLogin::instance()->get_user_info($openid, $access_token);

        if (empty($user))
        {
            $this->msg('获取用户信息出错');
        }
        $user['type'] = $type;
        $user['utype'] = Arr::get($query,'type');

        OpenLogin::login($user);
        $this->msg('', '/');
    }
	

    //退出登录
    public function action_logout()
    {
        OpenLogin::logout();
        $this->msg('', '/');
    }

    private function msg($msg, $url = '')
    {
        if (empty($msg))
        {
            header("Location: {$url}");
            exit;
        }
        $html = '<meta http-equiv="content-type" content="text/html;charset=utf-8"><script>';
        $html .= "alert('{$msg}');";
        if ($url != '') $html .= "location.href='{$url}';";
        $html .= '</script>';
        exit($html);
    }

}
